package com.core.enums.serializer;

import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.core.enums.IntEnum;

import java.lang.reflect.Type;


public class IntEnumSerializer implements ObjectSerializer, ObjectDeserializer {
    @Override
    public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
        Integer value = parser.parseObject(Integer.class);
        if (value == null) {
            return null;
        }
        T result = IntEnum.of(((Class<T>) type), value);
        if (result == null) {
            String format = String.format("枚举%s没有找到值%s", type.getTypeName(), value.toString());
            throw new RuntimeException(format);
        }
        return result;
    }

    @Override
    public int getFastMatchToken() {
        return 0;
    }

    @Override
    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) {
        if (object == null) {
            serializer.getWriter().writeNull();
            return;
        }
        SerializeWriter out = serializer.getWriter();
        IntEnum t = (IntEnum) object;
        String json = t.getValue() + "";
        out.write(json);
    }
}
